const { getList, 
        getDetail,
        newBlog,
        updateBlog,
        delBlog
    } = require('../controller/blog')
const {SuccessModel, ErrorModel} = require('../model/resModel')

const handleBoloRouter = (req, res) => {

    const method = req.method
    const id = req.query.id;

    // 获取博客列表
    if(method === "GET" && req.path === "/api/blog/list"){
        
        const author = req.query.author || ''
        const keyword = req.query.keyword || ''
        // const listData = getList(author, keyword)
        // 数据格式化
        // return new SuccessModel(listData)  
        const result = getList(author, keyword)
        return result.then(listData => {                  
            return new SuccessModel(listData)            
        })
        
    }

    // 获取一篇博客的内容
    if(method === "GET" && req.path === "/api/blog/detail"){
        // const data = getDetail(id)
        // return new SuccessModel(data)
        const result = getDetail(id)
        return result.then(detailData => {
            return new SuccessModel(detailData)
        })

    }

    // 新增一篇博客
    if(method === "POST" && req.path === "/api/blog/new"){
        // 假数据，在开发登录时传入真实数据
        // 这个author是当前登录用户的用户名
        req.body.author = "zhangsan"
        const result = newBlog(req.body)
        return result.then(data => {
            return new SuccessModel(data)
        })
        // return new SuccessModel(data)
    }

    // 更新一篇博客的内容
    if(method === "POST" && req.path === "/api/blog/update"){
        // if(result) {
        //     return new SuccessModel()
        // }else {
        //     return new ErrorModel("更新博客失败")
        // }
        const result = updateBlog(id, req.body)

        return result.then(val => {
            if(val) {
                return new SuccessModel()
            }else {
                return new ErrorModel('更新博客失败')
            }
        })
        
    }

    // 删除一篇博客的内容
    if(method === "POST" && req.path === "/api/blog/delete"){
        
        const author = 'lisi' // 假数据 开发登录时改为真实数据
        // 添加两重判断，无法通过id删除别人的blog
        const result = delBlog(id, author)
        // if(result){
        //     return new SuccessModel()
        // }else {
        //     return new ErrorModel("删除博客失败")
        // }
        return result.then(val => {
            if(val) {
                return new SuccessModel()
            } else {
                return new ErrorModel('删除博客失败')
            }
            
        })
    }
}

module.exports = handleBoloRouter